import {Link, useNavigate} from "react-router-dom";
import EmailIcon from "@src/assets/e-mail.svg?react";
import PsdIcon from "@src/assets/psd.svg?react";
import UserIcon from "@src/assets/user.svg?react";
import VerificationCodeIcon from "@src/assets/verification-code.svg?react"
import {Formik, FormikProps} from "formik";
import FormInputIcon from "@src/pages/logIn/_components/formInputIconProps";
import * as Yup from "yup";
import {useRequest} from "ahooks";
import {sendCode, usersRegister, usersRegisterFromType} from "@src/services/userinfo.ts";
import HeadList from "@src/components/headList";
import "./index.scss"
import VerifyCodeButton from "@src/pages/logIn/_components/verifyCodeButton";
import {useState} from "react";

export default function Enroll() {
    const sendCodeApi = useRequest(sendCode, {manual: true});
    const usersRegisterApi = useRequest(usersRegister, {manual: true});
    const [isDisabled, setIsDisabled] = useState(false);

    interface RegisterFromType extends usersRegisterFromType {
        newPassword: string;
    }

    const initialValues: RegisterFromType = {
        email: "",
        name: "",
        password: "",
        newPassword: "",
        verificationCode: "",
        avatar: "#"
    }
    const navigate = useNavigate();
    const validateEmail = (formik: FormikProps<RegisterFromType>) => {
        // 触发 email 字段的验证
        formik.setFieldTouched("email", true).then((value) => {
            if (value?.email == undefined) {
                sendCodeApi.runAsync(formik.values.email).then(() => setIsDisabled(true))
            } else {
                console.log(value.email)
            }
        });
    };

    return (
        <div className="card content">
            <div className="logo">注册账户</div>
            <Formik initialValues={initialValues}
                    validationSchema={Yup.object({
                        email: Yup.string().required('必填').email('无效的电子邮件地址').matches(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, '无效的电子邮件地址'),
                        name: Yup.string().required('必填').required("昵称是必须的哦~").matches(/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, '不能包含特殊字符').max(10,"长度最大为10"),
                        password: Yup.string().required('必填').min(6,"密码长度必须大于6"),
                        newPassword: Yup.string().required('必填').test(
                            'password-match',
                            '新密码必须与原密码一致',
                            function (value) {
                                // this 是当前字段的上下文，可以访问其他字段
                                return this.parent.password === value;
                            }
                        ),
                        verificationCode: Yup.string().required('必填'),
                    })}
                    onSubmit={(values) => {
                        console.log(JSON.stringify(values, null, 2));
                        usersRegisterApi.runAsync(values).then((data) => {
                            console.log(data)
                            navigate("/logIn");
                        })
                    }}>
                {(formik: FormikProps<RegisterFromType>) => (

                    <form onSubmit={formik.handleSubmit} className="from">

                        <div className="HeadList">
                            <p>选择头像</p>
                            <HeadList getHeadUrlData={(data) => formik.values.avatar = data[0]}
                                      onChange={(url) => formik.values.avatar = url}>
                            </HeadList>
                        </div>
                        <FormInputIcon
                            Icon={<UserIcon/>}
                            name="name"
                            placeholder="请输入昵称"
                            formik={formik}
                        />
                        <FormInputIcon
                            Icon={<PsdIcon/>}
                            name="password"
                            placeholder="请输入密码"
                            formik={formik}
                            type="password"
                        />
                        <FormInputIcon
                            Icon={<PsdIcon/>}
                            name="newPassword"
                            placeholder="请确认密码"
                            formik={formik}
                            type="password"
                        />

                        <FormInputIcon
                            Icon={<EmailIcon/>}
                            name="email"
                            placeholder="请输入邮箱"
                            formik={formik}
                            type="email"
                        />
                        <div className="verification-code">
                            <FormInputIcon
                                Icon={<VerificationCodeIcon/>}
                                name="verificationCode"
                                placeholder="请输入验证码"
                                formik={formik}
                            />
                            <VerifyCodeButton disabled={isDisabled} setDisabled={setIsDisabled}
                                              onGetCode={() => validateEmail(formik)}></VerifyCodeButton>
                        </div>


                        <button type="submit" className="z-button">注册</button>
                    </form>

                )}

            </Formik>
            <p>已有账户? <Link to="/logIn/register">立即登录</Link></p>
        </div>
    )
}